/*
 * ModificarRol.java
 *
 * Created on Oct 31, 2008, 6:41:25 PM
 */
package wasolicitudesfiec.Administracion.Roles;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.rave.web.ui.component.Button;
import com.sun.rave.web.ui.component.HiddenField;
import com.sun.rave.web.ui.component.ImageHyperlink;
import com.sun.rave.web.ui.component.Label;
import com.sun.rave.web.ui.component.Table;
import com.sun.rave.web.ui.component.TableColumn;
import com.sun.rave.web.ui.component.TextField;
import entidad.Personarol;
import entidad.Rol;
import hero.interfaces.UserSession;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import wasolicitudesfiec.SessionBean1;
import wasolicitudesfiec.RequestBean1;
import wasolicitudesfiec.ApplicationBean1;
import wasolicitudesfiec.Menu;
import wasolicitudesfiec.dataproviders.administracion.Dp_Persona;
import wasolicitudesfiec.logicacontrol.Logica;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @author kabad
 */
public class ModificarRol extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private Label lblRol = new Label();

    public Label getLblRol() {
        return lblRol;
    }

    public void setLblRol(Label l) {
        this.lblRol = l;
    }

    // </editor-fold>
    private Dp_Persona dp_Persona = new Dp_Persona();
    private TextField txtDescripcion = new TextField();

    public TextField getTxtDescripcion() {
        return txtDescripcion;
    }

    public void setTxtDescripcion(TextField tf) {
        this.txtDescripcion = tf;
    }
    private TableColumn tableColumn2 = new TableColumn();

    public TableColumn getTableColumn2() {
        return tableColumn2;
    }

    public void setTableColumn2(TableColumn tc) {
        this.tableColumn2 = tc;
    }
    private Table table1 = new Table();

    public Table getTable1() {
        return table1;
    }

    public void setTable1(Table t) {
        this.table1 = t;
    }
    private TableColumn tblColMatricula = new TableColumn();

    public TableColumn getTblColMatricula() {
        return tblColMatricula;
    }

    public void setTblColMatricula(TableColumn tc) {
        this.tblColMatricula = tc;
    }
    private ImageHyperlink imlinkRemover = new ImageHyperlink();

    public ImageHyperlink getImlinkRemover() {
        return imlinkRemover;
    }

    public void setImlinkRemover(ImageHyperlink ih) {
        this.imlinkRemover = ih;
    }
    private ImageHyperlink imlinkAgregarUsuario = new ImageHyperlink();

    public ImageHyperlink getImlinkAgregarUsuario() {
        return imlinkAgregarUsuario;
    }

    public void setImlinkAgregarUsuario(ImageHyperlink ih) {
        this.imlinkAgregarUsuario = ih;
    }
    private Button persona_id_btn = new Button();

    public Button getPersona_id_btn() {
        return persona_id_btn;
    }

    public void setPersona_id_btn(Button b) {
        this.persona_id_btn = b;
    }
    private HiddenField persona_id = new HiddenField();

    public HiddenField getPersona_id() {
        return persona_id;
    }

    public void setPersona_id(HiddenField hf) {
        this.persona_id = hf;
    }

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public ModificarRol() {
    }
    private int id;
    private Logica logica;

    @Override
    public void init() {
        FacesMessage message;
        try {
            // Perform initializations inherited from our superclass
            super.init();
            // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
            // Initialize automatically managed components
            // *Note* - this logic should NOT be modified
            try {
                _init();
            } catch (Exception e) {
                log("ModificarRol Initialization Failure", e);
                throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
            }

            // </editor-fold>
            logica = new Logica();
            if (!this.isPostBack()) {
                String idRol = (String) this.getExternalContext().getRequestParameterMap().get("id");
                if (idRol != null) {
                    this.getExternalContext().getSessionMap().put("id", idRol);
                }
                Rol rol = logica.leerRol(getId());
                if (rol == null) {
                    throw new Exception();
                //va al catch pero igual sigue la ejecucion ejemplo de modificar, habria que detener el rende o algo asi
                }
                this.getLblRol().setText(rol.getRol());
                this.getTxtDescripcion().setText(rol.getDescripcion());
                this.getDp_Persona().setListaRg_Persona(logica.leerVariosPersonasPoridRol(getId()));
                this.getMenu().setTitulo("Administracion - > Roles - > Modificar rol");
                boolean isEstudiante = logica.leerRol(getId()).getRol().equals("Estudiante");
                if (isEstudiante) {
                    this.getTblColMatricula().setRendered(true);
                } else {
                    this.getTblColMatricula().setRendered(false);
                }
            }
        } catch (Exception ex) {
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error no esperado, comuníquese con el administrador del sistema", ex.getLocalizedMessage());
            getFacesContext().addMessage(null, message);
            Logger.getLogger(ModificarRol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public Menu getMenu() {
        return (Menu) getBean("SolicitudesFIEC$Menu");
    }

    public Dp_Persona getDp_Persona() {
        return dp_Persona;
    }

    public void setDp_Persona(Dp_Persona dp_Persona) {
        this.dp_Persona = dp_Persona;
    }

    public String btnModificar_action() {
        FacesMessage message;
        try {
            Rol rol = new Rol();
            rol.setIdRol(getId());
            rol.setDescripcion((String) getTxtDescripcion().getText());
            rol.setRol((String) getLblRol().getText());
            logica.modificarRolMiembros(rol, this.getDp_Persona().getListaRg_Persona());
//            logica.addCookieMensaje("La operación fue exitosa", this.getExternalContext());
            return "roles";
        } catch (Exception ex) {
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error no esperado, comuníquese con el administrador del sistema", ex.getLocalizedMessage());
            getFacesContext().addMessage(null, message);
            Logger.getLogger(ModificarRol.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

    public String imlinkRemover_action() {
        FacesMessage message;
        try {
            String idP = (String) this.getExternalContext().getRequestParameterMap().get("idPersona");
            int idPersona = new Integer(idP);
            UserSession userSession = logica.getUserSession();
//            Personarol personarol = new Personarol();
//            personarol.setFkIdPersona(idPersona);
//            personarol.setFkIdRol(getId());
//            //verificar que no tenga procesos en curso , pero falta ver que sean procesos en los que actue como  el rol a borrar

            if (logica.leerProcesosEnCurso(userSession).isEmpty()) {
//                logica.eliminarPersonaRol(personarol);
                this.getDp_Persona().getListaRg_Persona().remove(logica.leerPersona(idPersona));
            } else {
                message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "No es posible remover el usuario del grupo, mientras tenga solicitudes en curso.", "");
                getFacesContext().addMessage(null, message);
            }
        } catch (Exception ex) {
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error no esperado, comuníquese con el administrador del sistema", ex.getLocalizedMessage());
            getFacesContext().addMessage(null, message);
            Logger.getLogger(ModificarRol.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public int getId() {
        String idRol;
        idRol = (String) this.getExternalContext().getSessionMap().get("id");

        return new Integer(idRol);
    }

    public void setId(int id) {
        this.id = id;
    }

    public String persona_id_btn_action() {
        FacesMessage message;
        int idPersona = Integer.parseInt((String) getPersona_id().getText());
        Personarol personarol = new Personarol();
        personarol.setFkIdPersona(idPersona);
        personarol.setFkIdRol(getId());
        try {
//            logica.nuevoPersonaRol(personarol);
            this.getDp_Persona().getListaRg_Persona().add(logica.leerPersona(idPersona));
        } catch (Exception ex) {
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrió un error no esperado, comuníquese con el administrador del sistema", ex.getLocalizedMessage());
            getFacesContext().addMessage(null, message);
            Logger.getLogger(ModificarRol.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

